package com.baihui.taobao.action;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.naming.NamingException;
import javax.sql.DataSource;

import net.sf.json.JSONObject;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.GeneDAO;
import com.baihui.taobao.db.OrderDAO;
import com.baihui.taobao.db.TradeDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BOrder;
import com.baihui.taobao.vo.BTrade;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.internal.mapping.ApiListField;
import com.taobao.api.internal.parser.json.ObjectJsonParser;
import com.taobao.api.request.TopatsResultGetRequest;
import com.taobao.api.request.TopatsTradesSoldGetRequest;
import com.taobao.api.response.TopatsResultGetResponse;
import com.taobao.api.response.TopatsTradesSoldGetResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;

public class TradeGet {
	static String appkey = "12531555";
	static String secret = "c0e2ae267999e52e63fde23cfedc140f";
	static String taobaourl = "http://gw.api.taobao.com/router/rest";
    static DataSource ds = null;
	protected TaoBaoSessionInfo sessionInfo;

	public static void main(String[] args) throws Exception {
		String yestoday = getYestoday();
		System.out.println(yestoday);
		System.out.println(getDate(-30, yestoday));
		String sessionkey = "61020278e634214ad1c54e153b28a8033cc143489952886405129440";
		List<Long> tids = new ArrayList<Long>();
//		tids.add(uploadtids(getDate(-30, yestoday), yestoday, sessionkey));
//		tids.add(uploadtids(getDate(-60, yestoday), getDate(-31, yestoday),
//				sessionkey));
//		tids.add(uploadtids(getDate(-90, yestoday), getDate(-61, yestoday),
//				sessionkey));
//		// tids.add(29247382l);
//		// tids.add(29247383l);
//		// tids.add(29247384l);
		ArrayList<String> files = new ArrayList<String>();
//		UnZip unZip = new UnZip();
//		while (true) {
//			while (tids.size() > 0) {
//				String fileName = downTids(tids.get(0));
//				if (fileName != null) {
//					if (!"该任务不存在".equals(fileName)) {
//						unZip.unZip(fileName, "D:\\taobaodate\\");
//						files.add("D:\\taobaodate\\" + tids.get(0));
//					}
//					tids.remove(0);
//				}
//			}
//			if (tids.size() == 0)
//				break;
//			else
//				Thread.sleep(1000 * 60 * 5);
//		}
		files.add("D:\\taobaodate\\29312271");
		files.add("D:\\taobaodate\\29312273");
		insertTrades(files);

	}

	public TradeGet(TaoBaoSessionInfo info) {
		this.sessionInfo = info;
	}

	public TaoBaoSessionInfo getSessionInfo() {
		return sessionInfo;
	}

	static void insertTrades(ArrayList<String> files) throws Exception {

		for (int i = 0; i < files.size(); i++) {
			BufferedReader bf = new BufferedReader(new FileReader(files.get(i)));
			String buff = null;
			int m = 0;
			while ((buff = bf.readLine()) != null) {
				buff = new String(buff.getBytes("utf-8"),"utf-8");
				List<Trade> tradeList = new ArrayList<Trade>();
				ObjectJsonParser<TradeFullinfoGetResponse> parser = new ObjectJsonParser<TradeFullinfoGetResponse>(
						TradeFullinfoGetResponse.class);
				TradeFullinfoGetResponse rsp = parser.parse(buff);
				Trade trade = rsp.getTrade();
				System.out.println(trade.getTid());
				if(trade.getTid() == 175125808722715L){
					System.out.println(trade.getTid());
				}
				tradeList.add(trade);

				// m++;
				// JSONObject jObject = new JSONObject().fromObject(buff);
				// JSONObject trade = jObject.getJSONObject(
				// "trade_fullinfo_get_response").getJSONObject("trade");
				// JSONArray orderArray = trade.getJSONObject("orders")
				// .getJSONArray("order");
				// Trade trades = null;
				// Object trade2 = fromJsonToJava(trade, Trade.class);
				// List<Order> orders2 = new ArrayList<Order>();
				// for (int j = 0; j < orderArray.size(); j++) {
				// Object object = fromJsonToJava(orderArray.getJSONObject(j),
				// Order.class);
				// orders2.add((Order) object);
				// }
				// trades = (Trade) trade2;
				// trades.setOrders(orders2);
				// tradeList.add(trades);
				// if (m == 100) {
				// insert(tradeList);
				// m = 0;
				// tradeList = new ArrayList<Trade>();
				// }
				insert(tradeList);
			}
			// if (m != 100)
			
		}
	}

	static void insert(List<Trade> tradeList) throws Exception {
		Connection cn = getConnection();
		TradeDAO tradeDAO = new TradeDAO();
		OrderDAO orderDAO = new OrderDAO();
		List<TaobaoObject> allInsertTrades = new ArrayList<TaobaoObject>(); // 存放修改过后的BTrade
		List<TaobaoObject> allInsertOrders = new ArrayList<TaobaoObject>(); // 存放修改过后的BOrder

		List<String> updateItems = new ArrayList<String>();
		for (Trade trade : tradeList) {
			boolean tradeInsert = true;
			// 如果在数据库中存在，则判断endtime是否为空，如果为空，更新，如果不为空，则直接过滤

			// 转换成我们的Info对象BTrade
			BTrade bTrade = new BTrade();
			// 拷贝源对象中的值到目标对象
			Util.copy(bTrade, trade);
			// 设置当前的用户ID
			bTrade.setUserId((long) 1111111);// getSessionInfo().getVisitor_id()
			bTrade.setExported(0);
			// cn = getConnection();
			allInsertTrades.add(bTrade);

			// 拼装交易中的订单，一次交易可能存在多个订单.
			if (trade.getOrders() != null && trade.getOrders().size() > 0) {
				// 过滤订单，此方法会获取已经在数据库中存在的订单。
				// List orderFilter = filter(trade.getOrders(), "oid",
				// "tborder");
				for (Order order : trade.getOrders()) {
					boolean orderInsert = true;
					// 如果在数据库中存在，则不处理.

					// 转换成我们的Info对象BOrder
					BOrder bOrder = new BOrder();
					// 拷贝源对象中的值到目标对象
					Util.copy(bOrder, order);
					// 设置当前用户ID和订单所属的父亲交易
					bOrder.setParent(trade);
					bOrder.setBuyerNick(trade.getBuyerNick());
					bOrder.setUserId((long) 1111111);// getSessionInfo().getVisitor_id()
					bOrder.setLotNo(1);
					bOrder.setExported(0);
					allInsertOrders.add(bOrder);
					updateItems
							.add("update titem set increamnum = (increamnum + "
									+ order.getNum()
									+ "),exported = 2 where num_iid = "
									+ order.getNumIid());
				}
			}

		}
		tradeDAO.insert(allInsertTrades, cn);
		orderDAO.insert(allInsertOrders, cn);
	}

	private static Date strToDate(String str) {
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sFormat.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	static String getValueFromjjson(JSONObject json, String field) {
		try {
			return json.getString(field);
		} catch (net.sf.json.JSONException e) {
			e.printStackTrace();
			return "";
		}
	}

	private static Object fromJsonToJava(JSONObject json, Class pojo)
			throws Exception {
		// 首先得到pojo所定义的字段
		Field[] fields = pojo.getDeclaredFields();
		// 根据传入的Class动态生成pojo对象
		Object obj = pojo.newInstance();
		for (Field field : fields) {
			// 设置字段可访问（必须，否则报错）
			field.setAccessible(true);
			// 得到字段的属性名
			String name = field.getName();
			char[] chars = name.toCharArray();
			for (int i = 0; i < chars.length; i++) {
				if (chars[i] < 97) {
					name = name.replace(chars[i] + "", "_"
							+ (char) (chars[i] + 32));
				}
			}
			System.out.print(name + "===");
			// 这一段的作用是如果字段在JSONObject中不存在会抛出异常，如果出异常，则跳过。
			try {
				json.get(name);
			} catch (Exception ex) {
				continue;
			}
			if (json.get(name) != null && !"".equals(json.getString(name))) {
				// 根据字段的类型将值转化为相应的类型，并设置到生成的对象中。
				if (field.getType().equals(Long.class)
						|| field.getType().equals(long.class)) {
					field.set(obj, Long.parseLong(json.getString(name)));
				} else if (field.getType().equals(String.class)) {
					field.set(obj, json.getString(name).replaceAll("\r\n", ""));
				} else if (field.getType().equals(Double.class)
						|| field.getType().equals(double.class)) {
					field.set(obj, Double.parseDouble(json.getString(name)));
				} else if (field.getType().equals(Integer.class)
						|| field.getType().equals(int.class)) {
					field.set(obj, Integer.parseInt(json.getString(name)));
				} else if (field.getType().equals(java.util.Date.class)) {
					field.set(obj, strToDate(json.getString(name)));
				} else {
					continue;
				}
			}
		}
		return obj;
	}

	/**
	 * 根据
	 * 
	 * @param domainClass
	 * @return
	 * @throws Exception
	 */
	public static String parseFields(Class domainClass) throws Exception {
		StringBuilder fields = new StringBuilder();
		innerParseFields(fields, domainClass, "");
		String ret = fields.toString();
		if (ret.endsWith(",")) {
			ret = ret.substring(0, ret.length() - 1);
		}
		return ret;
	}

	public static void innerParseFields(StringBuilder fields,
			Class domainClass, String prex) throws Exception {
		try {
			prex = (prex == null) ? "" : prex;

			BeanInfo beanInfo = Introspector.getBeanInfo(domainClass,
					Object.class);
			PropertyDescriptor[] descriptors = beanInfo
					.getPropertyDescriptors();
			for (PropertyDescriptor pd : descriptors) {
				Field field = domainClass.getDeclaredField(pd.getName());
				if (Util.isExist(field.getName(), GeneDAO.excludefield)) {
					continue;
				}
				ApiField apiField = field.getAnnotation(ApiField.class);
				if (apiField != null) {
					if (field.getType().getSimpleName().toUpperCase()
							.equals("LIST")) {
						ApiListField listField = field
								.getAnnotation(ApiListField.class);
						if (listField != null) {
							Type fieldType = field.getGenericType();
							if (fieldType instanceof ParameterizedType) {
								ParameterizedType paramType = (ParameterizedType) fieldType;
								Type[] genericTypes = paramType
										.getActualTypeArguments();
								if (genericTypes != null
										&& genericTypes.length > 0) {
									if (genericTypes[0] instanceof Class<?>) {
										Class<?> subType = (Class<?>) genericTypes[0];
										innerParseFields(fields, subType,
												listField.value());
									}
								}
							}
						}
					} else {
						if ("".equals(prex)) {
							fields.append(apiField.value()).append(",");
						} else {
							fields.append(prex + "." + apiField.value())
									.append(",");
						}

					}
				}
			}
		} catch (IntrospectionException e) {
			throw new Exception(e);
		}
	}

	public static long uploadtids(String starttime, String endtime,
			String sessionkey) throws Exception {
		System.out.println(starttime + "==" + endtime);
		long taskId = 0L;
		try {
			TaobaoClient client = new DefaultTaobaoClient(taobaourl, appkey,
					secret);
			TopatsTradesSoldGetRequest req = new TopatsTradesSoldGetRequest();
			req.setStartTime(starttime);
			req.setEndTime(endtime);
			req.setFields(parseFields(Trade.class));

			TopatsTradesSoldGetResponse response = client.execute(req,
					sessionkey);
			if (response.isSuccess()) {
				return response.getTask().getTaskId();
			} else {
				String subMsgString = response.getSubMsg();
				if (subMsgString.contains("TaskId=")) {
					taskId = Long.valueOf(subMsgString.substring(subMsgString
							.indexOf("TaskId=") + 7));
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return taskId;
	}

	public static String downTids(Long taskid) throws MalformedURLException,
			IOException, ApiException {

		// HttpServletRequest req = ServletActionContext.getRequest();
		// String pathString = req.getServletPath();
		String url = "";
		TaobaoClient client = new DefaultTaobaoClient(taobaourl, appkey, secret);
		TopatsResultGetRequest req1 = new TopatsResultGetRequest();
		req1.setTaskId(taskid);
		TopatsResultGetResponse response1 = client.execute(req1);
		if (response1.isSuccess()) {
			url = response1.getTask().getDownloadUrl();
		} else {
			return response1.getSubMsg();
		}
		if (url == null || url.equals(""))
			return null;
		System.out.println("开始下载" + new Date());
		int buffer = 2048;
		byte data[] = new byte[buffer];
		int count = -1;
		InputStream in = new URL(url).openStream();
		String fileName = "D://taobaodate/" + taskid + ".zip";
		OutputStream oStream = new FileOutputStream(fileName);

		while ((count = in.read(data, 0, buffer)) != -1) {
			oStream.write(data, 0, count);
		}
		System.out.println("结束下载" + new Date());

		return fileName;
	}

	public static String getYestoday() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.DATE, -1);
		return format.format(calendar.getTime());
	}

	public static String getDate(int length, String date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date day = null;
		try {
			day = format.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(day);
		calendar.add(calendar.DATE, length);
		return format.format(calendar.getTime());
	}

//	public static Connection getConnection() throws NamingException,
//			SQLException {
//		if (ds == null) {
//			Context ctx = new InitialContext();
//			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/test");
//		}
//		return ds.getConnection();
//	}
	
    public static Connection getConnection()  throws NamingException, SQLException {
		try{
			String jdbc_driver="com.mysql.jdbc.Driver";
			 String jdbc_url="jdbc:mysql://192.168.111.141:3306/taobao_new";  
			 String jdbc_username="bhdc001admin";
			 String jdbc_password="baihuizhadmin"; 
		  Class.forName(jdbc_driver);
		  return DriverManager.getConnection(jdbc_url, jdbc_username, jdbc_password);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		 
	
	}

}
